﻿using System;
using System.Collections.Generic;
using System.Reflection;
using MonsterLove.StateMachine;
using Unity.VisualScripting;
using UnityEngine;

namespace QFramework
{
    #region FSM

    public interface IFsmSystem:ICanSetArchitecture,ICanInit,ICanGetMono
    {
        Type StateType { get; } // 新增状态类型元数据
    }
    public interface ICanGetMono
    {
        void GetMono(MonoBehaviour monoBehaviour);
    }
    public interface ICanGetMonoReturn
    {
        IArchitecture GetMono(MonoBehaviour monoBehaviour);
    }
    public interface IFsmSystem<TState> : IFsmSystem where TState : Enum
    {
        // 继承基础接口并实现元数据
        Type IFsmSystem.StateType => typeof(TState);
    }

    public  abstract partial class Architecture<T> : IArchitecture where T : Architecture<T>, new()
    {
        // 添加智能注册方法
        public void RegisterFSMSystem<TSystem>(TSystem system) where TSystem : IFsmSystem
        {
            // 通过动态反射获取具体状态类型
            var stateType = system.StateType;
            // 激活基础方法
            var method = GetType().GetMethod(nameof(RegisterGenericSystem))
                ?.MakeGenericMethod(stateType, system.GetType());
            if (method != null) 
                method.Invoke(this, new object[] { system });
        }
        // 隐藏原始泛型方法（保持内部使用）
        public void RegisterGenericSystem<TState, TSystem>(TSystem system) 
            where TState : Enum
            where TSystem : IFsmSystem<TState>
        {
            system.SetArchitecture(this);
            mContainer.Register<TSystem>(system);

            if (mInited)
            {
                system.Init();
                system.Initialized = true;
            }
        }
        private static MonoBehaviour mono { get; set; }
        public IArchitecture SetMono(MonoBehaviour mono)
        {
            return this;
        }
        IArchitecture ICanGetMonoReturn.GetMono(MonoBehaviour monoBehaviour) => GetMono(monoBehaviour);
        public static IArchitecture GetMono(MonoBehaviour monoBehaviour)
        {
            mono = monoBehaviour;
            return Interface;
        }
    }



    // 抽象泛型状态机系统
    public abstract class AbstractFsmSystem<TState> : 
        AbstractSystem,
        IFsmSystem<TState>
        where TState : struct, Enum
    {
        private StateMachine<TState> fsm;

        protected void SetState(TState state)
        {
            fsm.ChangeState(state);
        }

        void ICanGetMono.GetMono(MonoBehaviour controller) => GetMono(controller);
        public void GetMono(MonoBehaviour controller)
        {
            fsm = StateMachine<TState>.Initialize(controller);
        }
    }

    #endregion
}